library(readr)
library(tidyverse)
library(ggpubr)
library(reshape2)

#------------------------------------------------------------------------------------------
## Method 7. Emotion Scores Using the DLUR Emotion Ontology Dictionary
#------------------------------------------------------------------------------------------

# Getting the Emotion Intensity Scores. This takes a long time (two days in our case). 
# If want to use output files directly for data analysis, skip to line 98.

Tok_Mob <- read_csv("Tokenization_Mob.csv")
Tok_Pac <- read_csv("Tokenization_Pac.csv")

DLD_Pac <- as.data.frame(1:dim(Tok_Pac)[1])
DLD_Mob <- as.data.frame(1:dim(Tok_Mob)[1])
Row_Pac <- as.data.frame(1:dim(Tok_Pac)[1])
Row_Mob <- as.data.frame(1:dim(Tok_Mob)[1])
Tok_Pac <- Tok_Pac[,-1]
Tok_Mob <- Tok_Mob[,-1]

colnames(DLD) <- c('word','POS','Meaning','Meaning_Num','Emotion','Indensity','Polarity','Sec_Emo','Sec_Indensity','Sec_Polarity')

for (i in 1:dim(DLD_Pac)[1]){
  for (n in 1:length(Tok_Pac[i,])){
    Row_Pac[i,n+1] <- match(Tok_Pac[i,n],DLD$word)
  }
}

for (i in 1:dim(DLD_Mob)[1]){
  for (n in 1:length(Tok_Mob[i,])){
    Row_Mob[i,n+1] <- match(Tok_Mob[i,n],DLD$word)
  }
}

write_csv(Row_Pac, file = "Row_PAC_Emotion.csv")
write_csv(Row_Mob, file = "Row_MOB_Emotion.csv")

Row_Mob <- Row_Mob[,-1]

Emotion <- c("PA","PE","PD","PH","PG","PB","PK","NA","NB","NJ","NH","PF",
             "NI","NC","NG","NE","ND","NN","NK","NL","PC")
Emotion_detection <- as.data.frame(matrix(0,nrow = dim(Tok_Mob)[1],ncol = 21))
colnames(Emotion_detection) <- Emotion

Mob_length <- c()
for (i in 1:dim(Row_Mob)[1]){
  Mob_length[i] <- length(Row_Mob[i,][!is.na(Row_Mob[i,])])
}
Mob_length <- as.data.frame(Mob_length)
colnames(Mob_length) <- c("length")
write_csv(Mob_length,"Mob_length.csv")

for (i in 1:dim(Mob_length)[1]){
  if (Mob_length$length[i] != 0){
    for (m in 1:Mob_length$length[i]){
      x <- Row_Mob[i,][!is.na(Row_Mob[i,])][m]
      for (n in 1:length(Emotion)){
        if (DLD$Emotion[x] == Emotion[n]){
          Emotion_detection[i,n] <- Emotion_detection[i,n] + DLD$Indensity[x]
        }
      }
    }
  }
}

write_csv(Emotion_detection,"Mob_Emotion_Detection.csv")

Row_Pac_Emotion <- Row_Pac_Emotion[,-1]
Emotion_detection_Pac <- as.data.frame(matrix(0,nrow = dim(Row_Pac_Emotion)[1],ncol = 21))
colnames(Emotion_detection_Pac) <- Emotion

Pac_length <- c()
for (i in 1:dim(Row_Pac_Emotion)[1]){
  Pac_length[i] <- length(Row_Pac_Emotion[i,][!is.na(Row_Pac_Emotion[i,])])
}

Pac_length <- as.data.frame(Pac_length)
colnames(Pac_length) <- c("length")
write.csv(Pac_length,"Pac_length.csv")

for (i in 1:dim(Pac_length)[1]){
  if (Pac_length$length[i] != 0){
    for (m in 1:Pac_length$length[i]){
      x <- Row_Pac_Emotion[i,][!is.na(Row_Pac_Emotion[i,])][m]
      for (n in 1:length(Emotion)){
        if (DLD$Emotion[x] == Emotion[n]){
          Emotion_detection_Pac[i,n] <- Emotion_detection_Pac[i,n] + DLD$Indensity[x]
        }
      }
    }
  }
}

write.csv(Emotion_detection_Pac,"Pac_Emotion_Detection.csv")

# Data Analysis
Row_Mob <- read.csv("Row_Mob_Emotion.csv")
Row_Mob <- Row_Mob[,3:length(Row_Mob)]
Row_Pac <- read.csv("Row_Pac_Emotion.csv")
Row_Pac <- Row_Pac[,-1]
Mob_Emotion_Detection <- read.csv("Mob_Emotion_Detection.csv")
Pac_Emotion_Detection <- read.csv("Pac_Emotion_Detection.csv")
Pac_Emotion_Detection <- Pac_Emotion_Detection[,-1]

## Preparing Data
Emotions <- rbind(Mob_Emotion_Detection,Pac_Emotion_Detection)

Happy <- Emotions$PA +Emotions$PE
Good <- Emotions$PD + Emotions$PH + Emotions$PG + Emotions$PB + Emotions$PK
Anger <- Emotions$'NA'
Sadness <- Emotions$NB + Emotions$NJ + Emotions$NH + Emotions$PF
Fear <- Emotions$NI + Emotions$NC + Emotions$NG
Disgust <- Emotions$NE + Emotions$ND + Emotions$NN + Emotions$NK + Emotions$NL
Surprise <- Emotions$PC

Emotions_7 <- do.call(rbind,Map(data.frame,Happy = Happy, Good = Good, Anger = Anger,
                                Sadness = Sadness, Fear = Fear, Disgust = Disgust, Surprise = Surprise))
NTU_Sentiment_Scores_All <- read_csv("NTU_Sentiment_Scores_All.csv")
Emotions_7['Type'] <- NTU_Sentiment_Scores_All$`Campaign Type`
Emotions_7['Campaigns'] <- NTU_Sentiment_Scores_All$Campaigns

# Set the sequence of the campaigns so that the graphs will follow this sequence
Campaign_Label <- c("India_1962","Soviet_1969","Vietnam_1974","Vietnam_1979",
                    "Japan_1990","Japan_1996","Japan_2005","Japan_2010","Japan_2012",
                    "Philippines_2016","India_2017")
Emotions_7$Campaigns <- factor(Emotions_7$Campaigns, levels = rev(Campaign_Label))

# Calculate the average emotion score for each emotion (total value/total length)
Emotions_7_Mob <- Emotions_7[1:dim(Row_Mob)[1],]
Ave_Emotions_7_Mob <- cbind(mean(Emotions_7_Mob$Happy),mean(Emotions_7_Mob$Good),mean(Emotions_7_Mob$Anger),
                            mean(Emotions_7_Mob$Sadness),mean(Emotions_7_Mob$Fear),mean(Emotions_7_Mob$Disgust),
                            mean(Emotions_7_Mob$Surprise))
Emotions_7_Pac <- Emotions_7[8686:9392,]
Ave_Emotions_7_Pac <- cbind(mean(Emotions_7_Pac$Happy),mean(Emotions_7_Pac$Good),mean(Emotions_7_Pac$Anger),
                            mean(Emotions_7_Pac$Sadness),mean(Emotions_7_Pac$Fear),mean(Emotions_7_Pac$Disgust),
                            mean(Emotions_7_Pac$Surprise))
Ave_Emotions_7 <- as.data.frame(rbind(Ave_Emotions_7_Mob,Ave_Emotions_7_Pac))
colnames(Ave_Emotions_7) <- c('Happy','Good','Anger','Sadness','Fear','Disgust','Surprise')
Ave_Emotions_7['Type'] <- c('Mobilization Campaigns','Pacification Campaigns')

# ==================== Figure 7.13 =====================================================

HappyT<- ggplot(data = Ave_Emotions_7,aes(x = Type, y = Happy, fill = Type)) +
  geom_bar(stat = 'summary') +
  scale_fill_manual(values = c('indianred','seagreen'))+
  labs(title = "Happy") + ylim(0,25) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

GoodT<- ggplot(data = Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Good, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Good") + ylim(0,130) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

SadnessT<- ggplot(data = Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Sadness, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Sadness") + ylim(0,10) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

AngerT<- ggplot(data = Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Anger, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Anger") + ylim(0,3)+
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

DisgustT<- ggplot(data = Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Disgust, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Disgust") + ylim(0,80) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

SurpriseT<- ggplot(data =Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Surprise, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Surprise") + ylim(0,1) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

FearT<- ggplot(data = Ave_Emotions_7) +
  geom_bar(mapping = aes(x = Type, y = Fear, fill = Type),stat = "summary") +
  scale_fill_manual(values = c('indianred','seagreen')) +
  labs(title = "Fear") + ylim(0,20) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10),axis.text.x = element_blank())

ggarrange(HappyT,GoodT,SadnessT,DisgustT,AngerT,SurpriseT,FearT,
          ncol = 7,nrow = 1,common.legend = TRUE,legend = 'bottom')

#Set to same Y axis
CAve_Emotions <- as.data.frame(t(Ave_Emotions_7_Mob))
CAve_Emotions['Pac'] <- t(Ave_Emotions_7_Pac)
Emotion_List <- c('Happy','Good','Anger','Sadness','Fear','Disgust','Surprise')
CAve_Emotions['Emotions'] <- Emotion_List
colnames(CAve_Emotions) <- c('Mobilization Campaigns','Pacification Campaigns','Emotion')
CAve_Emotions$Emotion <- factor(CAve_Emotions$Emotion, levels = Emotion_List)

CAve <- melt(CAve_Emotions,id.vars = 'Emotion')
colnames(CAve) <- c('Emotion','Type','Score')
ggplot(CAve,aes(x=Emotion,y=Score,fill=Type))+
  geom_bar(stat = 'identity',position = 'dodge') +
  scale_fill_manual(values = c('indianred','seagreen')) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10))

# ==================== Figure 7.14 =====================================================

Emotions['Type'] <- NTU_Sentiment_Scores_All$`Campaign Type`
Emotions['Campaigns'] <- NTU_Sentiment_Scores_All$Campaigns

# Count the length of detected emotions
Emo_D_split <- split(Emotions,Emotions$Type)
Emo_D_Mob <- Emo_D_split$`Mobilization Campaigns`
Emo_D_Pac <- Emo_D_split$`Pacification Campaigns`
Count_Emo_Mob <- colSums(Emo_D_Mob[,1:21])
Count_Emo_Pac <- colSums(Emo_D_Pac[,1:21])
Emotion <- colnames(Emotions[,1:21])
Count_Emo <- as.data.frame(Emotion)
Count_Emo['Mobilization Campaigns'] <- Count_Emo_Mob
Count_Emo['Pacification Campaigns'] <- Count_Emo_Pac
Emo_M_split <- split(Emo_D_Mob,Emo_D_Mob$Campaigns)
Emo_M_India1962 <- Emo_M_split$India_1962
Emo_M_Soviet1969 <- Emo_M_split$Soviet_1969
Emo_M_Vietnam1974 <- Emo_M_split$Vietnam_1974
Emo_M_Vietnam1979 <- Emo_M_split$Vietnam_1979
Count_Emo['India_1962'] <-colSums(Emo_M_India1962[,1:21])
Count_Emo['Soviet_1969'] <-colSums(Emo_M_Soviet1969[,1:21])
Count_Emo['Vietnam_1974'] <- colSums(Emo_M_Vietnam1974[,1:21])
Count_Emo['Vietnam_1979'] <- colSums(Emo_M_Vietnam1979[,1:21])
Emo_P_split <- split(Emo_D_Pac,Emo_D_Pac$Campaigns)
Count_Emo['Japan_1990'] <- colSums(Emo_P_split$Japan_1990[,1:21])
Count_Emo['Japan_1996'] <- colSums(Emo_P_split$Japan_1996[,1:21])
Count_Emo['Japan_2005'] <- colSums(Emo_P_split$Japan_2005[,1:21])
Count_Emo['Japan_2010'] <- colSums(Emo_P_split$Japan_2010[,1:21])
Count_Emo['Japan_2012'] <- colSums(Emo_P_split$Japan_2012[,1:21])
Count_Emo['Philippines_2016'] <- colSums(Emo_P_split$Philippines_2016[,1:21])
Count_Emo['India_2017'] <- colSums(Emo_P_split$India_2017[,1:21])

# Rank the emotion value by decreasing order
Rank_Emo_Total <- as.data.frame(Count_Emo[order(Count_Emo$`Mobilization Campaigns`,decreasing = TRUE),][,1])
colnames(Rank_Emo_Total) <- 'Mobilization Campaigns'
Rank_Emo_Total['Pacification Campaigns'] <- Count_Emo[order(Count_Emo$`Pacification Campaigns`,decreasing = TRUE),][,1]
Rank_Emo_Total['India_1962'] <- Count_Emo[order(Count_Emo$India_1962,decreasing = TRUE),][,1]
Rank_Emo_Total['Soviet_1969'] <- Count_Emo[order(Count_Emo$Soviet_1969,decreasing = TRUE),][,1]
Rank_Emo_Total['Vietnam_1974'] <- Count_Emo[order(Count_Emo$Vietnam_1974,decreasing = TRUE),][,1]
Rank_Emo_Total['Vietnam_1979'] <- Count_Emo[order(Count_Emo$Vietnam_1979,decreasing = TRUE),][,1]
Rank_Emo_Total['Japan_1990'] <- Count_Emo[order(Count_Emo$Japan_1990,decreasing = TRUE),][,1]
Rank_Emo_Total['Japan_1996'] <- Count_Emo[order(Count_Emo$Japan_1996,decreasing = TRUE),][,1]
Rank_Emo_Total['Japan_2005'] <- Count_Emo[order(Count_Emo$Japan_2005,decreasing = TRUE),][,1]
Rank_Emo_Total['Japan_2010'] <- Count_Emo[order(Count_Emo$Japan_2010,decreasing = TRUE),][,1]
Rank_Emo_Total['Japan_2012'] <- Count_Emo[order(Count_Emo$Japan_2012,decreasing = TRUE),][,1]
Rank_Emo_Total['Philippines_2016'] <- Count_Emo[order(Count_Emo$Philippines_2016,decreasing = TRUE),][,1]
Rank_Emo_Total['India_2017'] <- Count_Emo[order(Count_Emo$India_2017,decreasing = TRUE),][,1]

# Calculate the average emotion value (emotion value of campaign/length of each campaign)
Count_Emo_Ave <- as.data.frame(Emotion)
Count_Emo_Ave['Mobilization Campaigns'] <- Count_Emo$`Mobilization Campaigns`/dim(Emo_D_Mob)[1]
Count_Emo_Ave['Pacification Campaigns'] <- Count_Emo$`Pacification Campaigns`/dim(Emo_D_Pac)[1]
Count_Emo_Ave['India_1962'] <-Count_Emo$India_1962/dim(Emo_M_India1962)[1]
Count_Emo_Ave['Soviet_1969'] <-Count_Emo$Soviet_1969/dim(Emo_M_Soviet1969)[1]
Count_Emo_Ave['Vietnam_1974'] <- Count_Emo$Vietnam_1974/dim(Emo_M_Vietnam1974)[1]
Count_Emo_Ave['Vietnam_1979'] <- Count_Emo$Vietnam_1979/dim(Emo_M_Vietnam1979)[1]
Count_Emo_Ave['Japan_1990'] <- Count_Emo$Japan_1990/dim(Emo_P_split$Japan_1990)[1]
Count_Emo_Ave['Japan_1996'] <- Count_Emo$Japan_1996/dim(Emo_P_split$Japan_1996)[1]
Count_Emo_Ave['Japan_2005'] <- Count_Emo$Japan_2005/dim(Emo_P_split$Japan_2005)[1]
Count_Emo_Ave['Japan_2010'] <- Count_Emo$Japan_2010/dim(Emo_P_split$Japan_2010)[1]
Count_Emo_Ave['Japan_2012'] <- Count_Emo$Japan_2012/dim(Emo_P_split$Japan_2012)[1]
Count_Emo_Ave['Philippines_2016'] <- Count_Emo$Philippines_2016/dim(Emo_P_split$Philippines_2016)[1]
Count_Emo_Ave['India_2017'] <- Count_Emo$India_2017/dim(Emo_P_split$India_2017)[1]
write.csv(Count_Emo_Ave,"Count_Emo_Ave.csv")

Rank_Emo_Ave <- as.data.frame(Count_Emo_Ave[order(Count_Emo_Ave$`Mobilization Campaigns`,decreasing = TRUE),][,1])
colnames(Rank_Emo_Ave) <- 'Mobilization Campaigns'
Rank_Emo_Ave['Pacification Campaigns'] <- Count_Emo_Ave[order(Count_Emo_Ave$`Pacification Campaigns`,decreasing = TRUE),][,1]
Rank_Emo_Ave['India_1962'] <- Count_Emo_Ave[order(Count_Emo_Ave$India_1962,decreasing = TRUE),][,1]
Rank_Emo_Ave['Soviet_1969'] <- Count_Emo_Ave[order(Count_Emo_Ave$Soviet_1969,decreasing = TRUE),][,1]
Rank_Emo_Ave['Vietnam_1974'] <- Count_Emo_Ave[order(Count_Emo_Ave$Vietnam_1974,decreasing = TRUE),][,1]
Rank_Emo_Ave['Vietnam_1979'] <- Count_Emo_Ave[order(Count_Emo_Ave$Vietnam_1979,decreasing = TRUE),][,1]
Rank_Emo_Ave['Japan_1990'] <- Count_Emo_Ave[order(Count_Emo_Ave$Japan_1990,decreasing = TRUE),][,1]
Rank_Emo_Ave['Japan_1996'] <- Count_Emo_Ave[order(Count_Emo_Ave$Japan_1996,decreasing = TRUE),][,1]
Rank_Emo_Ave['Japan_2005'] <- Count_Emo_Ave[order(Count_Emo_Ave$Japan_2005,decreasing = TRUE),][,1]
Rank_Emo_Ave['Japan_2010'] <- Count_Emo_Ave[order(Count_Emo_Ave$Japan_2010,decreasing = TRUE),][,1]
Rank_Emo_Ave['Japan_2012'] <- Count_Emo_Ave[order(Count_Emo_Ave$Japan_2012,decreasing = TRUE),][,1]
Rank_Emo_Ave['Philippines_2016'] <- Count_Emo_Ave[order(Count_Emo_Ave$Philippines_2016,decreasing = TRUE),][,1]
Rank_Emo_Ave['India_2017'] <- Count_Emo_Ave[order(Count_Emo_Ave$India_2017,decreasing = TRUE),][,1]
write_csv(Rank_Emo_Ave,"Rank_Emo_Ave.csv")


Campaign_Mob_Ave <- (Count_Emo_Ave$India_1962+Count_Emo_Ave$Soviet_1969+Count_Emo_Ave$Vietnam_1974+Count_Emo_Ave$Vietnam_1979)/4
Campaign_Pac_Ave <- (Count_Emo_Ave$Japan_1990+Count_Emo_Ave$Japan_1996+Count_Emo_Ave$Japan_2005+Count_Emo_Ave$Japan_2010+Count_Emo_Ave$Japan_2012+
                       Count_Emo_Ave$Philippines_2016+Count_Emo_Ave$India_2017)/7
Count_Emo_CampaignAve <- as.data.frame(Emotion)
Count_Emo_CampaignAve['Mob'] <- Campaign_Mob_Ave
Count_Emo_CampaignAve['Pac'] <- Campaign_Pac_Ave
Rank_CampaignAve <- as.data.frame(Count_Emo_CampaignAve[order(Count_Emo_CampaignAve$Mob,decreasing = TRUE),][,1])
colnames(Rank_CampaignAve) <- 'Mobilization Campaigns'
Rank_CampaignAve['Pacification Campaigns'] <- Count_Emo_CampaignAve[order(Count_Emo_CampaignAve$Pac,decreasing = TRUE),][,1]

top_emo <- c('Praise','Condemnation','Hatred','Respect','Trust','Happiness')
Sample_Emo <- Count_Emo_CampaignAve[c(4,18,17,3,5,1),]
Sample <- as.data.frame(rep(top_emo,2))
Sample['Type'] <- c(rep('Mobilization Campaigns',6),rep('Pacification Campaigns',6))
Sample['Score'] <- c(Sample_Emo$Mob,Sample_Emo$Pac)
colnames(Sample) <- c('Emotion','Type','Score')
Sample$Emotion <- factor(Sample$Emotion,levels = top_emo)
ggplot(Sample,aes(x=Emotion,y=Score,fill=Type))+
  geom_bar(stat = 'identity',position = 'dodge') +
  scale_fill_manual(values = c('indianred','seagreen')) +
  geom_text(aes(label = round(Score,digits = 3)),color='white',position = position_dodge(width = 0.9),vjust=1.5) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(), plot.title = element_text(hjust = 0.5,size = 10))

